<template>
  <div class="swiper-container swiper" ref="swiper">
    <div class="swiper-wrapper">
      <div class="swiper-slide" v-for="(item, index) in banners" :key="index">
        <img class="swiper-img" :src="item.imgUrl" :alt="item.imgName" />
      </div>
    </div>
    <!-- 左右翻页器 -->
    <div class="swiper-button-next"></div>
    <div class="swiper-button-prev"></div>

    <!-- 底部小圆点 -->
    <div class="swiper-pagination"></div>
  </div>
</template>

<script>
import Swiper from 'swiper'
import 'swiper/css/swiper.min.css'
import { reqGetBannerList } from '@/api/home'
export default {
  data() {
    return {
      // 轮播图渲染所需数据
      banners: [],
    }
  },
  async mounted() {
    // 请求轮播图数据
    const result = await reqGetBannerList()
    this.banners = result

    // dom页面渲染完成后再启用轮播图
    this.$nextTick(() => {
      // 轮播图效果
      const mySwiper = new Swiper(this.$refs.swiper, {
        // 左右箭头
        navigation: {
          nextEl: '.swiper-button-next',
          prevEl: '.swiper-button-prev',
        },
        // 小圆点
        pagination: {
          el: '.swiper-pagination',
          // 点击圆点控制切换
          clickable: true,
          // 给一个类名,自定义样式
          // bulletClass: 'my-bullet',
          // 自定义活动样式类名
          // bulletActiveClass: 'my-bullet-active',
        },
        // 无缝切换
        loop: true,
        // 自动轮播
        autoplay: {
          delay: 1000,
          disableOnInteraction: false, //鼠标操作后,自动轮播继续,false为继续轮播,true为不自动轮播
        },
        // mousewheel: true,
        // keyboard: true,
      })
      // 鼠标移入则轮播停止
      mySwiper.el.onmouseenter = () => {
        mySwiper.autoplay.stop()
      }
      // 鼠标移出,轮播继续
      mySwiper.el.onmouseleave = () => {
        mySwiper.autoplay.start()
      }
    })
  },
}
</script>

<style lang="less" scoped>
// 翻页器和分页器样式
.swiper-container {
  // --swiper-theme-color: #ff6600; /* 设置Swiper风格 */
  --swiper-navigation-color: #fff; /* 单独设置按钮颜色 */
  --swiper-navigation-size: 20px; /* 设置按钮大小 */
  --swiper-pagination-color: #a7936e; /* 设置分页器颜色 */
}

.swiper {
  position: relative;
  .swiper-button-next,
  .swiper-button-prev {
    position: absolute;
    height: 50px;
    width: 50px;
    line-height: 50px;
    text-align: center;
    border-radius: 50%;
    background-color: #e2c199;
  }
  .swiper-button-next {
    right: 200px;
  }
  .swiper-button-next:hover {
    background-color: #cc9756;
  }
  .swiper-button-prev {
    left: 200px;
  }
  .swiper-button-prev:hover {
    background-color: #cc9756;
  }
}
</style>
